<template>
  <div id="map_container" class="map"></div>
</template>
<script setup lang="ts">
import {
  onMounted,
  ref
} from 'vue';

import { ElMessage } from 'element-plus';

import AMapLoader from '@amap/amap-jsapi-loader';

window._AMapSecurityConfig = {
  securityJsCode: '63222af0091e2b0c756785002c529e7e',
}
const { longitude, latitude, inputValAddress } = defineProps({
  longitude: {
    type: Number,
    default: 105.602725
  },
  latitude: {
    type: Number,
    default: 37.076636
  },
  inputValAddress: {
    type: String,
    default: ''
  },
})
const searchData = ref(null)
var map
var placeSearch
var geocoder
var getAddressByLocations
const emit = defineEmits(['update:longitude', 'update:latitude', 'update:inputValAddress'])
function initMap() {
  AMapLoader.load({
    key: 'fb5af7c98978e2782614ac03939c0134',
    version: '2.0', // 加载的JSAPI版本
    plugins: ['AMap.MapType', 'AMap.PlaceSearch', 'AMap.Geocoder'],//AMap.Scale尺寸插件  AMap.ToolBar放大缩小按钮  AMap.HawkEye右下角简略图  AMap.MapType图层类型  AMap.Geolocation  , 'AMap.AutoComplete'
  }).then(AMap => {
    map = new AMap.Map('map_container', {
      resizeEnable: true,
      viewMode: "2D",//是否为3D地图模式
      zoom: 5,// 1初始化地图级别
      center: [longitude, latitude],//初始化地图中心点位置
    })
    map.addControl(new AMap.MapType())
    var marker = new AMap.Marker({
      position: [longitude, latitude], //经纬度对象
      map: map
    });

    map.add(marker);
    map.on('click', (e) => {
      getAddressByLocations(e.lnglat.lng, e.lnglat.lat)
    })
    //输入提示
    var autoOptions = {
      input: "inputValAddress"
    };
    AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function () {
      var auto = new AMap.AutoComplete(autoOptions);
      placeSearch = new AMap.PlaceSearch({
        pageSize: 5, // 单页显示结果条数
        pageIndex: 1, // 页码 
        panel: false, // 结果列表将在此容器中进行展示。
        autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        map: map
      });
      auto.on("select", select);//注册监听，当选中某条记录时会触发
      function select(e) {
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name);  //关键字查询查询
      }
    });
    // 创建Geocoder插件实例
    geocoder = new AMap.Geocoder({
      radius: 1000,
      extensions: "all"
    });
    // 获取坐标名称的函数
    getAddressByLocations = function getAddressByLocation(lng, lat) {
      var location = new AMap.LngLat(lng, lat);
      geocoder.getAddress(location, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          map.remove(marker)
          marker = new AMap.Marker({
            position: [lng, lat], //经纬度对象
            zIndex: 999,
            map: map
          });
          map.add(marker);
          map.setCenter([lng, lat]);
          // 坐标对应的地址
          emit('update:inputValAddress', result.regeocode.formattedAddress)
          emit('update:longitude', lng)
          emit('update:latitude', lat)
        } else {
          ElMessage.error('未获取到具体信息')
          emit('update:inputValAddress', '')
        }
      });
    }
  })
}
function search(val) {
  searchData.value = val
  //构造地点查询类
  placeSearch.search(val, function (status, result) {
    if (status === 'complete' && result.info === 'OK') {
      //查询成功时，result 即对应匹配的 POI 信息
      if (result.poiList.pois?.length) {
        getAddressByLocations(result.poiList.pois[0].location.lng, result.poiList.pois[0].location.lat)
      } else {
        ElMessage.error('未查询到相关地址')
      }
    }
  })
}
onMounted(() => {
  initMap()
})
defineExpose({
  search
})
</script>
<style lang="scss" scoped>
.map {
  height: 500px;
  width: 500px;
}
</style>
